﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using DuJianliang.ApplicationPlatform.Common;
using DuJianliang.ApplicationPlatform.UserPermission;

namespace DuJianliang.ApplicationPlatform.Nonconforming
{
    public partial class NonconformingEdit : System.Web.UI.Page
    {
        Nonconformingl dal = new Nonconformingl();

        private string FlowInstanceID
        {
            get
            {
                if (ViewState["FlowInstanceID"] != null)
                {
                    return ViewState["FlowInstanceID"].ToString();
                }
                else
                {
                    string flowInstanceID = Guid.NewGuid().ToString();
                    ViewState["FlowInstanceID"] = flowInstanceID;
                    return flowInstanceID;
                }
            }
            set
            {
                ViewState["FlowInstanceID"] = value;
            }
        }

        private string Source
        {
            get
            {
                object obj = ViewState["Source"];
                return obj != null ? obj.ToString() : string.Empty;
            }
            set
            {
                ViewState["Source"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.FlowInstanceID = Request.QueryString["FlowInstanceID"];
                this.Source = Request.QueryString["Source"];

                InitControlData();
                SetControlState();
            }
        }

        private void InitControlData()
        {
            string sql = @"SELECT * FROM t5715_Nonconforming WHERE FlowInstanceID = @FlowInstanceID";

            Database database = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = database.GetSqlStringCommand(sql);
            database.AddInParameter(dbCommand, "@FlowInstanceID", DbType.String, this.FlowInstanceID);
            DataTable dataTable = database.ExecuteDataSet(dbCommand).Tables[0];

            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                DataRow row = dataTable.Rows[0];
                lblCode.Text = row["Code"].ToString();
                hidItemCode.Value = row["ItemCode"].ToString();
                txtItemCode.Text = row["ItemCode"].ToString();
                hidItemName.Value = row["ItemName"].ToString();
                txtItemName.Text = row["ItemName"].ToString();
                hidPartsNum.Value = row["PartsNum"].ToString();
                txtPartsNum.Text = row["PartsNum"].ToString();
                txtImgNum.Text = row["ImgNum"].ToString();
                txtBatchCount.Text = row["BatchCount"].ToString();
                txtNonconformingCount.Text = row["NonconformingCount"].ToString();
                txtWorkshop.Text = row["Workshop"].ToString();
                txtWorkTeam.Text = row["WorkTeam"].ToString();
                txtSupplier.Text = row["Supplier"].ToString();
            }
            else
            {
                lblCode.Text = dal.CreateApplyCode();
            }
        }

        private void SetControlState()
        {
            bool hasFlowData = false;
            bool flowCompleted = false;
            bool currentFlowStepIsFirstSetp = false;
            string flowEndOperation = string.Empty;

            if (!this.Source.ToLower().Equals("list"))
            {
                txtItemCode.Enabled = false;
                txtItemName.Enabled = false;
                txtPartsNum.Enabled = false;
                txtImgNum.Enabled = false;
                txtBatchCount.Enabled = false;
                txtNonconformingCount.Enabled = false;
                txtWorkshop.Enabled = false;
                txtWorkTeam.Enabled = false;
                txtSupplier.Enabled = false;
                btnSelectItemCode.Visible = false;
                btnSelectPartsNum.Visible = false;
                btnOK.Visible = false;
                btnCancel.Visible = false;

                return;
            }

            DataTable flowInstanceData = FlowHelper.GetFlowInstanceInfo(new Guid(this.FlowInstanceID));
            if (flowInstanceData != null && flowInstanceData.Rows.Count > 0)
            {
                currentFlowStepIsFirstSetp = FlowHelper.CurrentFlowStepIsFirstSetp(flowInstanceData.Rows[0]["FlowID"].ToString()
                    , this.FlowInstanceID);

                hasFlowData = true;

                if (flowInstanceData.Rows[0]["Completed"] != null)
                {
                    string strCompleted = flowInstanceData.Rows[0]["Completed"].ToString();

                    if (bool.TryParse(strCompleted, out flowCompleted) && flowCompleted)
                    {
                        if (flowInstanceData.Rows[0]["OperationID"] != null)
                        {
                            flowEndOperation = flowInstanceData.Rows[0]["OperationID"].ToString();
                        }
                    }
                }
            }

            if ((hasFlowData && !currentFlowStepIsFirstSetp))
            {
                txtItemCode.Enabled = false;
                txtItemName.Enabled = false;
                txtPartsNum.Enabled = false;
                txtImgNum.Enabled = false;
                txtBatchCount.Enabled = false;
                txtNonconformingCount.Enabled = false;
                txtWorkshop.Enabled = false;
                txtWorkTeam.Enabled = false;
                txtSupplier.Enabled = false;
                btnSelectItemCode.Visible = false;
                btnSelectPartsNum.Visible = false;
                btnOK.Visible = false;
            }            
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                UpdateData();
                Response.Redirect("NonconformingList.aspx");
            }
            catch
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('保存失败');</script>"); 
            }
        }

        private void UpdateData()
        {
            string sql_select = @"SELECT COUNT(FlowInstanceID) FROM dbo.t5715_Nonconforming WHERE FlowInstanceID = @FlowInstanceID";

            string sql_insert = @"INSERT INTO dbo.t5715_Nonconforming
                                       ([FlowInstanceID]
                                       ,[Code]
                                       ,[ItemCode]
                                       ,[ItemName]
                                       ,[ImgNum]
                                       ,[PartsNum]
                                       ,[BatchCount]
                                       ,[NonconformingCount]
                                       ,[WorkShop]
                                       ,[WorkTeam]
                                       ,[Supplier]
                                       ,[CreateUser]
                                       ,[CreateDate])
                                 VALUES
                                       (@FlowInstanceID
                                       ,@Code
                                       ,@ItemCode
                                       ,@ItemName
                                       ,@ImgNum
                                       ,@PartsNum
                                       ,@BatchCount
                                       ,@NonconformingCount
                                       ,@WorkShop
                                       ,@WorkTeam
                                       ,@Supplier
                                       ,@CreateUser
                                       ,GETDATE())";
            string sql_update = @"UPDATE dbo.t5715_Nonconforming
                                       SET 
                                          Code = @Code
                                          ,ItemCode = @ItemCode
                                          ,ItemName = @ItemName
                                          ,ImgNum = @ImgNum
                                          ,PartsNum = @PartsNum
                                          ,BatchCount = @BatchCount
                                          ,NonconformingCount = @NonconformingCount
                                          ,WorkShop = @WorkShop
                                          ,WorkTeam = @WorkTeam
                                          ,Supplier = @Supplier
                                          ,CreateUser = @CreateUser
                                      WHERE FlowInstanceID = @FlowInstanceID";

            try
            {

                Database database = DatabaseFactory.CreateDatabase();
                DbCommand dbCommand = database.GetSqlStringCommand(sql_select);
                database.AddInParameter(dbCommand, "@FlowInstanceID", DbType.String, this.FlowInstanceID );
                string count = database.ExecuteScalar(dbCommand).ToString();

                if (count.Equals("0"))
                {
                    dbCommand = database.GetSqlStringCommand(sql_insert);
                }
                else
                {
                    dbCommand = database.GetSqlStringCommand(sql_update);
                }

                database.AddInParameter(dbCommand, "@FlowInstanceID", DbType.String, this.FlowInstanceID);
                database.AddInParameter(dbCommand, "@Code", DbType.String, lblCode.Text);
                database.AddInParameter(dbCommand, "@ItemCode", DbType.String, hidItemCode.Value);
                database.AddInParameter(dbCommand, "@ItemName", DbType.String, hidItemName.Value);
                database.AddInParameter(dbCommand, "@ImgNum", DbType.String, txtImgNum.Text);
                database.AddInParameter(dbCommand, "@PartsNum", DbType.String, hidPartsNum.Value);
                database.AddInParameter(dbCommand, "@BatchCount", DbType.String, txtBatchCount.Text);
                database.AddInParameter(dbCommand, "@NonconformingCount", DbType.String, txtNonconformingCount.Text);
                database.AddInParameter(dbCommand, "@WorkShop", DbType.String, txtWorkshop.Text);
                database.AddInParameter(dbCommand, "@WorkTeam", DbType.String, txtWorkTeam.Text);
                database.AddInParameter(dbCommand, "@Supplier", DbType.String, txtSupplier.Text);
                database.AddInParameter(dbCommand, "@CreateUser", DbType.String, CurrentInfo.Instance.CurrentUser.UserName);
                database.ExecuteNonQuery(dbCommand);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("NonconformingList.aspx");
        }
    }
}